package cn.lingyangwl.agile.model.enums;

import cn.lingyangwl.agile.model.constants.*;
import cn.lingyangwl.framework.tool.core.exception.BizException;
import lombok.AllArgsConstructor;
import lombok.Getter;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 配置定义枚举, 主要应多多配置场景, 比如一个存储配置会有多个渠道, minio, oss, 七牛云等等, 他们都属于存储配置
 * , 又比如短信渠道, 阿里云短信, 七牛云短信, 华为元短信等等, 他们都属于短信配置
 *
 * @author shenguangyang
 */
@Getter
@AllArgsConstructor
public enum ConfigDefineEnum {
    DEFAULT("默认", null, ofKeys(ConfigKeyEnum.DEFAULT)),
    STORAGE("存储", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.STORAGE_MINIO, ConfigKeyEnum.STORAGE_ALIYUN)),
    SMS("短信", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.SMS_ALIYUN, ConfigKeyEnum.SMS_JUMEI, ConfigKeyEnum.SMS_TENCENT)),
    EMAIL("邮件", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.EMAIL_163, ConfigKeyEnum.EMAIL_TENCENT)),

    WX_MA("微信小程序", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.WX_MA)),
    WX_MP("微信公众号", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.WX_MP)),
    WX_CP("企业微信", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.WX_CP)),
    DINGTALK("钉钉", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.DINGTALK)),
    GITEE("Gitee", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.GITEE)),

    WEB_SITE("租户信息", DataIsolateLevel.ALONE, ofKeys(ConfigKeyEnum.WEB_SITE)),
    PUSH_PC("PC端消息推送", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.PUSH_SYSTEM_PC)),
    PUSH_APP("APP端消息推送", DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.PUSH_APP)),
    COPYRIGHT("版权",  DataIsolateLevel.MAIN, ofKeys(ConfigKeyEnum.COPYRIGHT)),
    USER_REGISTER("用户注册", DataIsolateLevel.ALONE, ofKeys(ConfigKeyEnum.USER_REGISTER)),
    ;

    /**
     * 名称
     */
    private final String name;

    /**
     * 配置隔离级别
     */
    private final DataIsolateLevel isolateLevel;

    private final List<ConfigKeyEnum> keys;

    private final static Map<String, ConfigDefineEnum> map = new HashMap<>();

    static {
        for (ConfigDefineEnum value : ConfigDefineEnum.values()) {
            value.keys.stream().map(ConfigKeyEnum::getKey).forEach(e -> map.put(e, value));
        }
    }

    static List<ConfigKeyEnum> ofKeys(ConfigKeyEnum... keys) {
        return Arrays.stream(keys).collect(Collectors.toList());
    }

    /**
     * 如果能找到就采用 code, 否则返回 configKey
     */
    public static ConfigDefineEnum ofByKey(String configKey) {
        ConfigDefineEnum configDefineEnum = map.get(configKey);
        if (Objects.isNull(configDefineEnum)) {
            throw new BizException("尚未包含配置定义, configKey: {}", configKey);
        }
        return configDefineEnum;
    }

    public static ConfigDefineEnum ofByKey(ConfigKeyEnum configKey) {
        if (Objects.isNull(configKey)) {
            throw new BizException("configKey is null");
        }
        return ofByKey(configKey.getKey());
    }
}
